import FileSystemManager from "../base/FileSystemManager";
import { ResultState, ResultCallback, DataCallback } from "../SDKConfig";
/**
 * https://developers.weixin.qq.com/minigame/dev/api/file/FileSystemManager.readFileSync.html
 */
export default class WXFileSystem extends FileSystemManager {


    constructor() {
        super();
        this.fs = wx.getFileSystemManager();
    }
    writeFile(fileName: string, data: any, encoding, callback: ResultCallback) {
        let filePath = wx['env'].USER_DATA_PATH + '/' + fileName;
        console.log('writeFile filePath ', filePath)
        this.fs.writeFile({
            filePath: filePath,  //写入的文件路径
            data: data,  //写入的文本
            encoding: encoding,  //字符编码格式
            success: function () { //成功回调
                console.log(' writeFile ok')
                callback(ResultState.YES)
            },
            fail: function (err) {  //失败回调
                console.log(' writeFile fail ', err)
                callback(ResultState.NO)
            },
            complete: function () {  //完成回调
                console.log(' writeFile complete')
            }
        })
    }

    readFile(fileName, encoding, callback: DataCallback) {
        let filePath = wx['env'].USER_DATA_PATH + '/' + fileName;
        console.log('readFile filePath ', filePath)
        this.fs.readFile({
            filePath: filePath,  //写入的文件路径
            encoding: encoding,  //字符编码格式
            success: function (res) { //成功回调
                console.log(' readFile ok')
                // console.log('res.data ', res.data)
                // let bytes: Uint8Array = new Uint8Array(res.data)
                console.log(' res.data.length ',res.data.length)
                var buffer = new ArrayBuffer(res.data.length);
                var dataview = new DataView(buffer);

                for (var i = 0; i < res.data.length; i++) {
                    dataview.setUint8(i,res.data[i])
                }

                var ints = new Uint8Array(buffer);
                callback(ResultState.YES, ints)
            },
            fail: function (err) {  //失败回调
                console.log(' readFile fail', err)
                callback(ResultState.NO, null)
            },
            complete: function () {  //完成回调
                console.log(' writeFile complete')
            }
        })
    }
    writeFileSync(fileName: string, data: string | ArrayBuffer, encoding: string) {
        let filePath = wx['env'].USER_DATA_PATH + '/' + fileName;
        let result = this.fs.writeFileSync(filePath, data, encoding)
        return result
    }

    readFileSync(fileName: string, encoding: string) {
        let filePath = wx['env'].USER_DATA_PATH + '/' + fileName;
        return this.fs.readFileSync(filePath, encoding)
    }


}
